package day_2022_9_to_12.Day;

/**
 * @author haomin
 * @date 2022/09/05 23:51
 **/
public class Day3_10_Offer58_ReverseWords {
    class Solution {
        public String reverseWords(String s) {
            s = s.trim();
            String[] arr = s.split(" ");
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < arr.length; ++i){
                if(arr[i].length() == 0) continue;
                if(i != arr.length-1){
                    sb.append(reverse(arr[i])).append(" ");
                }else sb.append(reverse(arr[i]));
            }
            sb.reverse();
            return sb.toString();
        }
        private String reverse(String str){
            char[] ch = str.toCharArray();
            int l = 0, r = ch.length-1;
            while(l <= r){
                char temp = ch[l];
                ch[l] = ch[r];
                ch[r] = temp;
                l++; r--;
            }
            return new String(ch);
        }
    }
    class Solution2 {
        public String reverseWords(String s) {
            s = s.trim();
            String[] arr = s.split(" ");
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < arr.length; ++i){
                if(arr[i].length() == 0) continue;
                if(i != arr.length-1){
                    sb.append(new StringBuffer(arr[i]).reverse()).append(" ");
                }else sb.append(new StringBuffer(arr[i]).reverse());
            }
            sb.reverse();
            return sb.toString();
        }
    }
}